/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：太平金科-基础组件封装层-ElasticSearch-缺省实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taipingframework.boot.es.conditions.query;

import com.taipingframework.boot.es.conditions.AbstractLambdaWrapper;
import com.taipingframework.boot.es.toolkit.support.SFunction;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Objects;

public class LambdaQueryWrapper<T> extends AbstractLambdaWrapper<T, LambdaQueryWrapper<T>>
        implements Query<LambdaQueryWrapper<T>, T, SFunction<T, ?>> {

    /**
     * 不建议直接 new 该实例，使用 Wrappers.<T>lambdaQuery()
     */
    public LambdaQueryWrapper() {
        super.initNeed();
    }

    @Override
    protected void finalize() throws Throwable {
        super.clear();
        super.finalize();
    }

    //region implements Query<Children, T, R>

    /**
     * 分组：GROUP BY 字段, ...
     * <p>例: groupBy("id", "name")</p>
     *
     * @param aggregationBuilder 聚合统计
     * @return children
     */
    @Override
    public LambdaQueryWrapper<T> groupBy(AbstractAggregationBuilder aggregationBuilder) {
        if (Objects.isNull(aggregationBuilder)) {
            return typedThis;
        }

        super.aggregationBuilders.add(aggregationBuilder);

        return typedThis;
    }

    /**
     * 排序：ORDER BY 字段, ...
     * <p>例: orderBy(true, "id", "name")</p>
     *
     * @param isAsc  是否是 ASC 排序
     * @param column 字段
     * @return children
     */
    @Override
    public LambdaQueryWrapper<T> orderBy(boolean isAsc, SFunction<T, ?> column) {
        if (Objects.isNull(column)) {
            return typedThis;
        }

        SortOrder mode = isAsc ? SortOrder.ASC : SortOrder.DESC;
        super.sortBuilders.add(SortBuilders.fieldSort(columnToString(column)).order(mode));

        return typedThis;
    }

    //endregion

}
